import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
import JSONbig from 'json-bigint'

// 创建 JSONbig 实例，配置将大整数转换为字符串
const JSONBigInt = JSONbig({ storeAsString: true })

// create an axios instance
const service = axios.create({
  // baseURL: 'https://xkygl.hbnu.edu.cn/api',
  // baseURL: 'http://218.197.18.189:9800/api',
  baseURL: 'http://localhost:9528',
  timeout: 30000, // request timeout
  // 使用自定义的 transformResponse 处理大整数
  transformResponse: [function(data) {
    if (typeof data === 'string') {
      try {
        // 使用 json-bigint 解析，自动将大整数转换为字符串
        return JSONBigInt.parse(data)
      } catch (e) {
        return data
      }
    }
    return data
  }]
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      // 创建业务错误对象，添加标识
      const businessError = new Error(res.msg || 'Error')
      businessError.isBusinessError = true
      businessError.originalData = res
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('提示信息', '确认退出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            // location.reload()
            router.push('/login') // 跳转到登录页
          })
        })
      } else {
        // 对于其他业务错误，统一显示错误提示
        Message.error(res.msg || '操作失败')
      }
      return Promise.reject(businessError)
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    // 优先判断业务错误（任何错误响应中包含msg字段的情况）
    if (error.response && error.response.data && error.response.data.msg) {
      // 创建业务错误对象，添加标识
      const businessError = new Error(error.response.data.msg)
      businessError.isBusinessError = true
      businessError.originalData = error.response.data
      // 显示业务错误消息
      Message.error(error.response.data.msg || '操作失败')
      return Promise.reject(businessError)
    }
    // 检查HTTP状态码是否为50014，这是后端设置的token过期状态码
    if (error.response && error.response.status === 50014) {
      // to re-login
      MessageBox.confirm('登录超时', '确认退出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          router.push('/login') // 跳转到登录页
        })
      })
      // 创建token过期错误对象，添加标识
      const tokenError = new Error('Token expired')
      tokenError.isTokenExpired = true
      return Promise.reject(tokenError)
    }
    // 其他网络错误统一显示提示
    if (!error.isBusinessError) {
      error.isNetworkError = true
      Message.error('网络请求失败，请稍后重试')
    }
    return Promise.reject(error)
  }
)

export default service
